<template>
  <div class='container'>
    <el-card class="box-card">
      <div class="title">试题录入</div>
      <el-form 
        ref="form" 
        :model="form" 
        label-width="80px" 
        :rules="rules"
      >
         <el-form-item 
          label="学科:" 
          prop="subjectID"
        >
          <el-select 
            v-model="form.subjectID" 
            placeholder="请选择" 
            class="form-with" 
            @change="onSubjectChange"
          >
            <el-option 
              :label="item.label" 
              :value="item.value" 
              v-for="item in simpleList.data" 
              :key="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item 
          label="目录:" 
          prop="catalogID"
        >
          <el-select 
            v-model="form.catalogID" 
            placeholder="请选择" 
            class="form-with"
          >
            <el-option 
              :label="item.label" 
              :value="item.value" 
              v-for="item in directorysSimpleList.data" 
              :key="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item 
          label="企业:" 
          prop="enterpriseID"
        >
          <el-select 
            v-model="form.enterpriseID" 
            placeholder="请选择" 
            class="form-with"
          >
            <el-option 
              :label="item.company" 
              :value="item.id" 
              v-for="item in companyList.items" 
              :key="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item 
          label="城市:" 
          prop="province"
         
        >
          <el-select 
            v-model="form.province" 
            placeholder="请选择" 
            class="form-with-city"
            @change="onChangeProvince"
          >
            <el-option
              :label="province"
              :value="province"
              v-for="(province, i) in getProvincesList"
              :key="i"
            >
            </el-option>
          </el-select>
          <el-select 
            v-model="form.city" 
            placeholder="请选择" 
            class="form-with-city"
          >
            <el-option
              :label="city"
              :value="city"
              v-for="(city, i) in getCityList"
              :key="i"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item 
          label="方向:" 
          prop="direction"
        >
          <el-select 
            v-model="form.direction" 
            placeholder="请选择" 
            class="form-with"
          >
            <el-option 
              :label="item" 
              :value="item" 
              v-for="item in getDirection" 
              :key="item"
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item 
          label="题型:" 
          prop="questionType"
        >
          <el-radio-group v-model="form.questionType">
            <el-radio 
              :label="item.label" 
              v-for="item in questionType" 
              :key="item.value"
            >
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item 
          label="难度:" 
          prop="difficulty"
        >
          <el-radio-group v-model="form.difficulty">
            <el-radio 
              :label="item.label" 
              v-for="item in difficulty" 
              :key="item.value"
            >
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item 
          label="题干:" 
          prop="question"
        >
          <quill-editor
              v-model="form.question"
              ref="myQuillEditor"
              :options="editorOption"
          >
          </quill-editor>
        </el-form-item>
         <el-form-item 
          label="选项:" 
          v-show="form.questionType === '单选' || form.questionType === '多选'"
        >
        </el-form-item>
        <!-- 单选框 -->
        <div  
          v-for="(item, i) in array" 
          :key="i"
        >
          <el-form-item v-if="i < 4 && form.questionType === '单选'">
              <el-radio 
                v-model="radio" 
                :label="i"
              >
                {{item.code}}
              </el-radio>
              <el-input 
                v-model="item.title" 
                class="form-with"
              >
              </el-input>
              <el-upload
              class="avatar-uploader"
              action="http://hmmm-api.itheima.net/questions"
              :show-file-list="false"
              v-model="item.img"
              >
              <img 
                v-if="item.img" 
                :src="item.img" 
                class="avatar"
              >
              <span 
                v-else 
                class="uploading"
              >
                上传图片
              </span>
              <i class="el-icon-circle-close"></i>
            </el-upload>
          </el-form-item>
        </div>
        <!-- 多选框 -->
        <div 
          v-for="(item, i) in array" 
          :key="item.code"
        >
          <el-checkbox-group v-model="form.checkList">
            <el-form-item v-if="i < count && form.questionType === '多选'">
              <el-checkbox :label="i">{{item.code}}</el-checkbox>
              <el-input 
                v-model="item.title" 
                class="form-with checkbox"
              >
              </el-input>
              <el-upload
                class="avatar-uploader"
                action="http://hmmm-api.itheima.net/questions"
                :show-file-list="false"
                v-model="item.img"
                >
                <img 
                  v-if="item.img" 
                  :src="item.img" 
                  class="avatar"
                >
                <span 
                  v-else 
                  class="uploading"
                >
                  上传图片
                </span>
                <i class="el-icon-circle-close"></i>
              </el-upload>
            </el-form-item>
          </el-checkbox-group>
        </div>
        <!-- 按钮 -->
        <div>
              <el-button 
                type="danger" 
                class="btn" 
                :disabled="form.questionType === '单选'" 
                @click="onAddCheckbox" 
                v-show="form.questionType === '单选' || form.questionType === '多选'"
              >
                +增加选项与答案
              </el-button>
        </div>
        <el-form-item label="解析视频:">
          <el-input 
            v-model="form.videoURL" 
            class="form-with"
          >
          </el-input>
        </el-form-item>
        <el-form-item 
          label="答案解析:" 
          prop="answer"
        >
          <quill-editor
              v-model="form.answer"
              ref="myQuillEditor"
              :options="editorOption"
          >
          </quill-editor>
        </el-form-item>
        <el-form-item label="题目备注:">
          <el-input 
            type="textarea" 
            v-model="form.remarks" 
            class="form-with"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="试题标签:">
          <el-select 
            v-model="form.tags" 
            placeholder="请选择" 
            class="form-with"  
            multiple
          >
            <el-option 
              :label="item.label" 
              :value="item.value" 
              v-for="item in tagsSimpleList.data" 
              :key="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="onSubmit('form')"
          >
            确认提交
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
let currentId = null
const questionTypeMapping = new Map([
  ['多选', '2'],
  ['单选', '1'],
  ['简答', '3']
])
const difficultyMapping = new Map([
  ['一般', '2'],
  ['简单', '1'],
  ['困难', '3']
])
import * as citysApi from '../../api/hmmm/citys';
import { mapActions, mapState } from 'vuex'
import {array, difficulty, questionType} from '../../api/hmmm/constants'
import * as constantsApi from '../../api/hmmm/constants'
import * as questionApi from '../../api/hmmm/questions'
export default {
  name: 'QuestionNewList',
  data () {
    return {
      array,
      difficulty,
      questionType,
      count: 4,
      imageUrl: '',
      radio: '',
      loading: false,
      form: {
        checkList: [],
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '单选',
        difficulty: '简单',
        question: '',
        options:[],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: '',
      },
      checkList: {},
      page: 1,
      pageSize: 10,
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'blur' },
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'blur' }
        ],
        enterpriseID: [
          {required: true, message: '请选择企业', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '请选择市区', trigger: 'blur' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'blur' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        question: [
          { required: true, message: '请填写题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请填写答案解析', trigger: 'blur' }
        ]
      },
      editorOption: {
        modules: {
          toolbar: {
            container:[
              ['bold', 'italic', 'underline', 'strike'],
              ['blockquote', 'code-block'],
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],
              ['link', 'image']
            ],
            handlers: {
              'image': function(value) {
                if (value) {
                    document.querySelector('.edit-uploader input').click()
                } else {
                    this.quill.format('image', false);
                }
                // this.$refs.aUpload.click() //自定义图片上传回调
              }
            }
          },
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      },
    }
  },
  computed: {
    ...mapState('questions', ['questionList', 'questionDetail']),
    ...mapState('subject', ['simpleList']),
    ...mapState('userSimple', ['userSimpleList']),
    ...mapState('tags', ['tagsSimpleList']),
    ...mapState('directorys', ['directorysSimpleList']),
    ...mapState('company', ['companyList']),
    // 获取城市列表
    getProvincesList() {
      return citysApi.provinces()
    },
    // 获取城市下边地区列表
    getCityList() {
    return citysApi.citys(this.form.province)
    },
    // 获取方向
    getDirection() {
      return constantsApi.direction
    },
    // 获取题型
    getDuestionType() {
      return constantsApi.questionType
    },
    // 获取难度
    getDifficulty() {
      return constantsApi.difficulty
    },
  },
  methods: {
    ...mapActions('questions', ['updateQuetionList', 'updateQuetionDetail']),
    ...mapActions('subject', ['updateSimpleList']),
    ...mapActions('userSimple', ['updateUserSimpleList']),
    ...mapActions('tags', ['updateTagsSimpleList']),
    ...mapActions('directorys', ['updateDirectorysSimpleList']),
    ...mapActions('company', ['updateCompanyList']),
    // 获取二级目录/标签
    onSubjectChange(val) {
      this.updateTagsSimpleList({id: val})
      this.updateDirectorysSimpleList({id: val})
    },

    beforeEditorUpload() {
      // 显示loading动画
      this.quillUpdateImg = true
    },

    editorUploadSuccess(res, file) {
      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill
      // 如果上传成功
      if (res.code === 0) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片  res.info为服务器返回的图片地址
        quill.insertEmbed(length, 'image', res.data.filepath)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        this.$message.error('图片插入失败')
      }
      // loading动画消失
      this.quillUpdateImg = false
    },
    // 富文本图片上传失败
    editorUploadError() {
      // loading动画消失
      this.quillUpdateImg = false
      this.$message.error('图片插入失败')
    },
    // 点击增加按钮
    onAddCheckbox() {
      this.count++
    },
    // 点击提交
    async onSubmit(form) {
      switch(this.form.questionType) {
        case '单选':
          this.form.options = this.array
            .filter((_, i) => i < 4)
            .map((d, i) =>({
              ...d,
              isRight: this.radio === i 
            }))
          break;
        case '多选':
          this.form.options = this.array
            .filter((_, i) => i < this.count)
            .map((d, i) => ({
              ...d,
              isRight: this.form.checkList.some(d => d === i)
            }))
          break;
        default:
          break;
      }
      if (this.$route.query.id) {
        questionApi.update({
          id: this.$route.query.id,
          ...this.form,
          difficulty: difficultyMapping.get(this.form.difficulty),
          questionType: questionTypeMapping.get(this.form.questionType),
        })
          .then(res => this.$message.success('修改成功'))
          .catch(err => this.$message.error('修改失败'))
      }else {
        await questionApi.add({
        ...this.form,
        difficulty: difficultyMapping.get(this.form.difficulty),
        questionType: questionTypeMapping.get(this.form.questionType),
      })
        .then(res => this.$message.success('新增成功'))
        .catch(err => this.$message.error('新增失败'))
      }
      // 跳转基础题库
      this.$router.push('list')
      // 重置表单
      this.$refs.form.resetFields();
      this.array.map(d => ({
        ...d,
        isRight: false,
        code: '',
        title: '',
        img: '',
      }))

    },
    onChangeProvince(val) {
      this.form.city = citysApi.citys(val)[0]
      
    }

  },
  async created () {
    this.loading = true
    await this.updateSimpleList()
    this.updateQuetionList()
    this.updateUserSimpleList()
    this.updateCompanyList({pagesize: 1000})
    if(this.$route.query.id) {
      await this.updateQuetionDetail({id: this.$route.query.id})
      this.form.subjectID = this.questionDetail.subjectID,
      this.form.catalogID = this.questionDetail.catalogID,
      this.form.enterpriseID = this.questionDetail.enterpriseID,
      this.form.province = this.questionDetail.province,
      this.form.city = this.questionDetail.city,
      this.form.direction = this.questionDetail.direction,
      this.form.questionType = this.questionDetail.questionType,
      this.form.difficulty = this.questionDetail.difficulty,
      this.form.question = this.questionDetail.question,
      this.form.options = this.questionDetail.options,
      this.form.videoURL = this.questionDetail.videoURL,
      this.form.answer = this.questionDetail.answer,
      this.form.remarks = this.questionDetail.remarks,
      this.form.tags = this.questionDetail.tags
    }
    this.loading = false
  }
}
</script>

<style scoped lang='scss'>
.container {
  padding: 16px;

  .title{
    height: 40px;
    width: 100%;
    border-bottom: 1px solid #eee;
    margin-bottom: 16px;
  }

  .form-with {
    width: 400px;
  }
  .checkbox {
    margin-left: 20px;
  }
  .avatar-uploader {
    margin-left: 8px;
    // float: right;
    display: inline-block;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    width: 100px;
    height: 70px;
    position: relative;
    // overflow: hidden;


    .el-icon-circle-close {
      position: absolute;
      display: inline-block;
      font-size: 16px;
      right: -10px;
      top: -5px;
      background-color: #fff;
    }
  }
  .avatar-uploader:hover {
    border-color: #409EFF;
  }
  .uploading {
    display: inline-block;
    font-size: 16px;
    color: #8c939d;
    width: 100px;
    height: 70px;
    line-height: 70px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 70px;
    display: block;
  }

  ::v-deep .ql-editor {
    height: 300px;
  }
  .btn {
    margin-left: 80px;
    margin-bottom: 16px;
  }
}


</style>
